package mini.expr.math;

import mini.Proc;
import mini.compiler.CodeGenerator;
import mini.expr.Expr;

import java.util.HashMap;
import java.util.LinkedList;

public class Times extends Expr {

    private Expr e1,  e2;

    public Times(Expr op1, Expr op2) {
        e1 = op1;
        e2 = op2;
    }
    
    public Integer eval(HashMap<String, Integer> nametable, HashMap<String, Proc> functiontable, LinkedList var) {
        return new Integer(e1.eval(nametable, functiontable, var) * e2.eval(nametable, functiontable, var));
    }

    /**
     * Parse routine from slide 8 is:
     * <ol>
     * <li>Store result of op1 in t1
     * <li>Store result of op2 in t2
     * <li>Load result of op1 (stored in t1) to accumulator
     * <li>Multiply to accumulator the result of op2 (stored in t2)
     * <li>Store accumulator to t3
     * </ol>
     */
    public String parse(HashMap<String,Integer> hm, HashMap<String, Proc> functiontable, LinkedList var) {
    	
    	CodeGenerator cg = new CodeGenerator();
    	
    	// Keep track of the temp variable
    	hm.put(getTempVariable(), null);

    	// Load operands 1 and 2 to memory
    	cg.appendCode( e1.parse(hm,functiontable,var) );
    	cg.appendCode( e2.parse(hm,functiontable,var) );
    	
    	// Load operand 1 to the accumulator
    	cg.addLoadAccumulator( e1.getTempVariable() );
    	
    	// Multiply operand 2 to what's in the accumulator
    	cg.addMultiply( e2.getTempVariable() );
    	
    	// Store the result
    	cg.addStoreAccumulator( getTempVariable() );
    	
    	// Return the result
    	return cg.getCode();
    }
}
